﻿/*
    File name:          SerialSTK
    File type:          Class
    Author:             Sune Krog-Meyer 09888
    Creation date:      05-05-2011
    Description:        Contains STK-calls for the robot.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace i4pro_gruppe_d.RobotCommunication
{
    public class SerialSTK
    {
        private SerialPort sp;

        /// <summary>
        /// Classconstructor
        /// </summary>
        /// <param name="port"> Comport to communicate through </param>
        /// <param name="baud"> baudrate (has to be the same as the STK-kit) </param>
        /// <param name="parity"> Parity </param>
        /// <param name="dataBits"> Databits </param>
        /// <param name="stopBits"> Stopbits </param>
        public SerialSTK(string port = "COM4", int baud = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            sp = new SerialPort(port, baud, parity, dataBits, stopBits);
        }

        /// <summary>
        /// Opens for communication
        /// </summary>
        /// <returns> True if opened, false otherwise </returns>
        public bool Open()
        {
            if (!sp.IsOpen)
                sp.Open();

            if (!sp.IsOpen)
                return true;
            return false;
        }

        /// <summary>
        /// Closes for communication
        /// </summary>
        /// <returns> True if closed, false otherwise </returns>
        public bool Close()
        {
            if(sp.IsOpen)
                sp.Close();
            
            if (!sp.IsOpen)
                return true;
            return false;
        }

        /// <summary>
        /// Reads an ADC value
        /// </summary>
        /// <returns> Value from the ADC </returns>
        public double ReadADC()
        {
            sp.Write("a");
            System.Threading.Thread.Sleep(5000);
            return Convert.ToDouble(sp.ReadExisting());        
        }
    }
}
